package pub.tbc.rubbish.client.discovery;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import pub.tbc.rubbish.client.discovery.cache.ServiceCache;
import pub.tbc.rubbish.client.discovery.zk.ZKService;
import pub.tbc.rubbish.client.factory.ObjectFactory;
import pub.tbc.toolkit.Objs;

import java.util.List;

/**
 * 1. 判断本地缓存，是否有该服务的地址；
 * 2. 如果有，判断是否大于一个，是则调用负载方法（先简单随机一下，不轮洵，那个需要保存状态，也不加权，也不用哈希；
 * 3. 如果没有，同步一下zk，刷新缓存
 * 4. 如果还没有，异常
 *
 * @author tbc on 2016/12/7 12:16:33.
 */
@Slf4j
public class DefaultDiscovery implements Discovery {
    private ServiceCache cache = ObjectFactory.getServiceCache();

    @Override
    public String discover(String serviceName) {
        // 检查缓存
        List<String> addresses = cache.get(serviceName);
        if (Objs.nonEmpty(addresses)) return LoadBalancingHelper.simpleRandom(addresses);

        // 服务中心操作实例（该实例中将完成获取数据及注册监听）
        ServiceConnection serviceConnection = ObjectFactory.getServiceConnection();
        serviceConnection.listener(serviceName);
        cache.flush(serviceName, serviceConnection.getChildrenForPath(serviceName));

        return LoadBalancingHelper.simpleRandom(cache.get(serviceName));
    }

    private String getServiceName(String path) {
        return getElementForEnd(path, "/", 2);
    }

    private String getServiceAddress(String path) {
        return getElementForEnd(path, "/", 1);
    }

    /**
     * 字符串拆成数组，获取数组的倒数第几个元素
     *
     * @param path  。
     * @param index 。
     * @return 。
     */
    private String getElementForEnd(String path, String divide, int index) {
        if (Objs.isEmpty(path))
            return null;
        String[] ss = path.split(divide);
        return ss[ss.length - index];
    }

    private void eventDebugLog(PathChildrenCacheEvent event) {
        log.debug("event-type:" + event.getType().name() + "; event-path: " + event.getData().getPath());
    }

}
